//
//  ProjectImagesViewController.m
//  OutesIOS
//
//  Created by norman on 2019/1/26.
//  Copyright © 2019 norman. All rights reserved.
//

#import "ProjectImagesViewController.h"
#import "UITapView.h"
#import "MWPhotoBrowser.h"
#import "UITapImageView.h"
#import "ProjectImageManager.h"

#define IMG_PADDING 5
#define kPagePadding 15
#define IMG_SIZE (kScreen_Width  - 2*kPagePadding -2*IMG_PADDING)/3

@interface ProjectImagesViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate, MWPhotoBrowserDelegate> {
    MBProgressHUD *HUD;
    BOOL editModel;
}

@property (nonatomic,strong) UIView *contentView;
@property (nonatomic,strong) UITapView *addPhotoView;
@property (nonatomic,strong) NSMutableArray *picDataSource;
@property (nonatomic,strong) UILabel *lbTip;


@end

@implementation ProjectImagesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"项目照片";
    
    //自定义返回按钮
    UIBarButtonItem *returnBtn = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(onReturn)];
    self.navigationItem.leftBarButtonItem = returnBtn;
    
    UIBarButtonItem *publish =[[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(publishMessage)];
    self.navigationItem.rightBarButtonItem = publish;
    
    [self setupViews];
    // Do any additional setup after loading the view.
}

- (void)setupViews {
    self.contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Out_NavAndStatus_Height)];
    self.contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contentView];
    //6、长按手势
    UILongPressGestureRecognizer *longpressGesutre=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongpressGesture:)];
    //长按时间为1秒
    longpressGesutre.minimumPressDuration=1;
    //允许15秒中运动
    longpressGesutre.allowableMovement=15;
    //所需触摸1次
    longpressGesutre.numberOfTouchesRequired=1;
    [self.contentView addGestureRecognizer:longpressGesutre];
    
    self.lbTip = [UILabel labelSingleLineboldFontSize:kListDetailFontSize content:@"长按屏幕可以删除图片"];
    self.lbTip.width += 5;
    self.lbTip.textColor = CM_TABLE_DETAIL_COLOR;
    self.lbTip.hidden = YES;
    self.lbTip.centerX = kScreen_Width/2;
    [self.contentView addSubview:self.lbTip];
    
//    UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
//    [self.contentView addGestureRecognizer:tapGesturRecognizer];

    self.addPhotoView = [[UITapView alloc]initWithFrame:CGRectMake(kPagePadding, kPagePadding, IMG_SIZE, IMG_SIZE)];
    self.addPhotoView.backgroundColor = [UIColor whiteColor];
    self.addPhotoView.layer.borderColor = UIColor16(0xebebf1).CGColor;
    self.addPhotoView.layer.borderWidth = 1;
    self.addPhotoView.tag = 1;
    [self.contentView addSubview:self.addPhotoView];
    @weakObj(self);
    [self.addPhotoView addTargetsBlock:^(id obj) {
        [Weakself setEditModel:NO];
        [Weakself pickerFromPhotoLib];
    }];
    UIImageView *add = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"plus_icon"]];
    add.centerX = IMG_SIZE/2;
    add.centerY = IMG_SIZE/2;
    [self.addPhotoView addSubview:add];
    
    self.contentView.height = CGRectGetMaxY(self.addPhotoView.frame) + kPagePadding;
    
    [self setupImageView];
}

- (void)setupImageView {
    self.picDataSource = [NSMutableArray new];
    if (![Tools isEmpty:self.images]) {
        NSArray *a = [self.images componentsSeparatedByString:@","];
        for (NSString *image_path in a) {
            ProjectImageManager *manager = [ProjectImageManager new];
            manager.path = image_path;
            manager.needUpload = NO;
            [self.picDataSource addObject:manager];
            [self addImageView];
        }
    }
}

- (void)addImageView {
    int currentRow = (int)(self.picDataSource.count - 1)/3;
    int currentCol = (self.picDataSource.count - 1)%3;
    CGFloat x = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentCol;
    CGFloat y = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentRow;
    ProjectImageManager *manager = [self.picDataSource objectAtIndex:self.picDataSource.count - 1];
    UITapImageView *imageView = [[UITapImageView alloc] init];
    if (manager.needUpload) {
        [imageView setImage:manager.image];
    } else {
        [imageView sd_setImageWithURL:[Tools getResourceFullPathURL:manager.path]];
    }
    imageView.frame = CGRectMake(x, y, IMG_SIZE, IMG_SIZE);
    imageView.tag = 1000 + self.picDataSource.count - 1;
    imageView.clipsToBounds = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    @weakObj(self)
    [imageView addTargetBlock:^(id obj) {
        UITapImageView *view = (UITapImageView *)obj;
        [Weakself startImageBrowser:view.tag - 1000];
    }];
    [self.contentView addSubview:imageView];
    
    //图片上显示删除按钮
    UITapView *view = [[UITapView alloc]initWithFrame:CGRectMake(x, y, IMG_SIZE, IMG_SIZE)];
    @weakObj(view);
    
    [view addTargetsBlock:^(id obj) {
        //删除图片
        [Weakself deleteOneImage:(Weakview.tag - 10000)];
    }];
    view.backgroundColor = UIColorAlphaRGB(0.1, 0.1, 0.1, 0.8);
    view.tag = self.picDataSource.count - 1 + 10000;
    
    UIImageView *close = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"delete_image"]];
    close.centerX = view.width/2;
    close.centerY = view.height/2;
    [view addSubview:close];
    view.hidden = !editModel;
    [self.contentView addSubview:view];
    
    
    currentRow = (int)self.picDataSource.count/3;
    currentCol = (self.picDataSource.count)%3;
    self.addPhotoView.x = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentCol;
    self.addPhotoView.y = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentRow;
    
    if (self.picDataSource.count > 0) {
        self.lbTip.hidden = NO;
        self.lbTip.y = CGRectGetMaxY(self.addPhotoView.frame) + kPagePadding;
        self.contentView.height = CGRectGetMaxY(self.lbTip.frame) + kPagePadding;
    } else {
        self.lbTip.hidden = YES;
        self.contentView.height = CGRectGetMaxY(self.addPhotoView.frame) + kPagePadding;
    }
    
}

- (void)onReturn {
    if ([self imageHasChanged]) {
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"项目照片未保存，要返回吗！" cancelButtonTitle:@"确定" otherButtonTitles:[NSArray arrayWithObjects:@"取消", nil] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)publishMessage {
    //先去上传图片
    NSMutableArray *updateImages = [NSMutableArray new];
    if (self.picDataSource.count > 0) {
        for (ProjectImageManager *manager in self.picDataSource) {
            if (manager.needUpload) {
                [updateImages addObject:manager.image];
            }
        }
    }
    if (updateImages.count > 0) {
        [self uploadImage:updateImages andResult:^(BOOL result) {
            if (result) {
                [self setProjectImage];
            } else {
                [Tools showMessageCenter:@"照片上传失败"];
            }
        }];
    }
    else {
        [self setProjectImage];
    }
}

- (BOOL)imageHasChanged {
    BOOL changed = NO;
    if ([Tools isEmpty:self.images]) {
        if (self.picDataSource.count > 0) {
            changed = YES;
        } else {
            changed = NO;
        }
    } else if (self.picDataSource.count == 0) {
        changed = YES;
    } else if (self.picDataSource.count > 0
               && self.picDataSource.count == [self.images componentsSeparatedByString:@","].count) {
        for (ProjectImageManager *manager in self.picDataSource) {
            if (![self.images containsString:manager.path]) {
                changed = YES;
                break;
            }
        }
    } else {
        changed = YES;
    }
    return changed;
}

- (void)setProjectImage {
    if (![self imageHasChanged]) {
        return;
    }
    
    NSMutableArray *paths = [NSMutableArray new];
    for (ProjectImageManager *manager in self.picDataSource) {
        [paths addObject:manager.path];
    }
    
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setObject:self.project_id forKey:@"project_id"];
    [param setObject:[paths componentsJoinedByString:@","] forKey:@"images"];
    [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
    NSString *url;
    if (self.is_5c) {
        url = HTTP_GET_PROJECT_IMAGE_SET;
    } else {
        url = HTTP_GET_HEAT_PROJECT_IMAGE_SET;
    }
    [HttpClient getWithUrl:url token:[AccountManager manager].token paramDic:param resultClass:[CommonResponse class] success:^(CommonResponse *response) {
        [MBProgressHUD hideHUDForView:self.view];
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"项目照片设置成功！" cancelButtonTitle:@"确定" otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            self.images = [NSString stringWithFormat:@"%@", [paths componentsJoinedByString:@","]];
            if (self.imageChanged != nil) {
                self.imageChanged([paths componentsJoinedByString:@","]);
            }
            //刷新消息列表
            [self.navigationController popViewControllerAnimated:YES];
        }];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [Tools showMessageBottom:@"服务器异常，请重试！"];
    }];
}



- (void)deleteOneImage:(NSInteger)index {
    int currentRow, currentCol;
    for (UIView *sub in self.contentView.subviews) {
        NSInteger pos = sub.tag;
        if (sub.tag >= 10000) {
            pos -= 10000;
        }
        else if (sub.tag >= 1000) {
            pos -= 1000;
        }
        else {
            continue;
        }
        if (pos == index) {
            //删除视图
            [sub removeFromSuperview];
        }
        else if (pos > index){
            //移动
            pos--;
            sub.tag = sub.tag - 1;
            currentRow = (int)(pos)/3;
            currentCol = (pos)%3;
            sub.x = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentCol;
            sub.y = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentRow;
        }
    }
    [self.picDataSource removeObjectAtIndex:index];
    
    currentRow = (int)self.picDataSource.count/3;
    currentCol = (self.picDataSource.count)%3;
    self.addPhotoView.x = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentCol;
    self.addPhotoView.y = kPagePadding + (IMG_SIZE + IMG_PADDING)*currentRow;
    
    if (self.picDataSource.count > 0) {
        self.lbTip.hidden = NO;
        self.lbTip.y = CGRectGetMaxY(self.addPhotoView.frame) + kPagePadding;
        self.contentView.height = CGRectGetMaxY(self.lbTip.frame) + kPagePadding;
    } else {
        self.lbTip.hidden = YES;
        self.contentView.height = CGRectGetMaxY(self.addPhotoView.frame) + kPagePadding;
    }
}

- (void)handleLongpressGesture:(UILongPressGestureRecognizer*)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        return;
    }
    [self setEditModel:!editModel];
}

- (void)tapAction:(id)sender {
    [self setEditModel:NO];
}

- (void)setEditModel:(BOOL)edit {
    editModel = edit;
    for (UIView *sub in self.contentView.subviews) {
        if ([sub isKindOfClass:[UITapView class]] && sub.tag >= 10000) {
            sub.hidden = !editModel;
        }
    }
    if (!editModel) {
        self.lbTip.text = @"长按屏幕可以删除照片";
    } else {
        self.lbTip.text = @"长按屏幕取消删除照片";
    }
}

- (void)setCellDImageSource:(NSArray*)imageSource editMOdel:(Boolean)editModel {
    if (imageSource != nil && imageSource.count > 0) {
        for (UIView *sub in self.contentView.subviews) {
            if ([sub isKindOfClass:[UITapImageView class]] && sub.tag >= 1000) {
                NSInteger pos = sub.tag - 1000;
                if (imageSource.count > pos) {
                    ((UITapImageView*)sub).image = [imageSource objectAtIndex:pos];
                }
                else {
                    ((UITapImageView*)sub).image = nil;
                }
            }
            else if ([sub isKindOfClass:[UITapView class]] && sub.tag >= 10000) {
                NSInteger pos = sub.tag - 10000;
                if (imageSource.count > pos) {
                    sub.hidden = !editModel;
                }
                else {
                    sub.hidden = YES;
                }
            }
        }
    }
}



#pragma mark - 图片浏览器代理

/**
 启动图片浏览器
 */
- (void)startImageBrowser:(NSInteger) position {
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    
    // Set options
    browser.displayActionButton = NO; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    //        browser.wantsFullScreenLayout = YES; // iOS 5 & 6 only: Decide if you want the photo browser full screen, i.e. whether the status bar is affected (defaults to YES)
    
    // Optionally set the current visible photo before displaying
    [browser setCurrentPhotoIndex:position];
    
    // Present
    [self.navigationController pushViewController:browser animated:YES];
    
}

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    return self.picDataSource.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    //    if (index < self.photos.count)
    //        return [self.photos objectAtIndex:index];
    if (index < self.picDataSource.count) {
        ProjectImageManager *manager = [self.picDataSource objectAtIndex:index];
        MWPhoto *photo;
        if (manager.needUpload) {
            photo = [MWPhoto photoWithImage:manager.image];
//            [imageView setImage:manager.image];
        } else {
            photo = [MWPhoto photoWithURL:[Tools getResourceFullPathURL:manager.path]];
        }
        return photo;
    }
    return nil;
    
}

#pragma mark - 图片选择器代理
//完成选取
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    // 判断，图片是否允许修改
    UIImage *image;
    if ([picker allowsEditing]){
        //获取用户编辑之后的图像
        image = [info objectForKey:UIImagePickerControllerEditedImage];
    } else {
        // 照片的元数据参数
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    ProjectImageManager *manager = [ProjectImageManager new];
    manager.needUpload = YES;
    manager.image = image;
    [self.picDataSource addObject:manager];
    [picker dismissViewControllerAnimated:YES completion:^{
        //设置视图
        [self addImageView];
    }];
}


// 取消选取
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}


#pragma mark -选取图片
/**
 添加图片
 */
- (void)pickerFromPhotoLib {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"选择要添加的照片" message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction: [UIAlertAction actionWithTitle:@"相机" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self openCamera];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle:@"照片库" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self openPhotoLibrary];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated: YES completion: nil];
}

/**
 *  调用照相机
 */
- (void)openCamera {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO; //可编辑
    //判断是否可以打开照相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else {
        [Tools showMessageBottom:@"打开相机失败！"];
    }
}



/**
 *  打开相册
 */

-(void)openPhotoLibrary {
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.allowsEditing = NO;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.navigationBar.translucent = NO;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    else {
        [Tools showMessageBottom:@"打开相册失败！"];
    }
}

#define DEFAULT_IMAGE_WIDTH 1200

- (void)uploadImage:(NSArray*)images andResult:(void (^)(BOOL))result{
    NSMutableArray *data = [NSMutableArray new];
    NSMutableArray *mime = [NSMutableArray new];
    
    if (images.count > 0) {
        for (int i = 0; i < images.count; i++) {
            
            NSData* imageData;
            NSString *mimeType;
            
            //对图片进行压缩处理
            UIImage *image = [images objectAtIndex:i];
            if (image.size.width > DEFAULT_IMAGE_WIDTH) {
                CGSize size;
                size.width = DEFAULT_IMAGE_WIDTH;
                size.height = image.size.height * DEFAULT_IMAGE_WIDTH/image.size.width;
                image = [self imageWithImage:image scaledToSize:size];
            }
            
            imageData = UIImageJPEGRepresentation(image, 0.9);
            mimeType = @"image/jpeg";
            
            if (imageData == nil) {
                //返回为png图像。
                imageData = UIImagePNGRepresentation(image);
                mimeType = @"image/png";
            }
            
            if (imageData == nil) {
                [Tools showMessageCenter:@"图片格式不支持，请重试"];
                return;
            }
            [data addObject:imageData];
            [mime addObject:mimeType];
        }
    }
    [MBProgressHUD showMessage:@"照片上传中..." toView:self.view];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@?token=%@&project_id=%@", HTTP_HOST, HTTP_POST_PROJECT_IMAGE_BATCH_UPLOAD, [AccountManager manager].token, self.project_id];
    [HttpClient postUploadImage:urlStr andMimeType:mime andData:data resultClass:[ProjectData class] success:^(ProjectData *obj) {
        [MBProgressHUD hideHUDForView:self.view];
        if (![Tools isEmpty:obj.images]) {
            for (NSString *path in [obj.images componentsSeparatedByString:@","]) {
                for (ProjectImageManager *manager in self.picDataSource) {
                    if (manager.needUpload) {
                        manager.path = path;
                        manager.needUpload = NO;
                        break;
                    }
                }
            }
        }
        result(YES);
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        result(NO);
    }];
}

/**
 *  对图片尺寸进行压缩
 *
 *  @param image   image description
 *  @param newSize <#newSize description#>
 *
 *  @return <#return value description#>
 */
- (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize {
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    return newImage;
}


/**
 改变下系统图片选择控件的导航栏title颜色
 
 @param navigationController <#navigationController description#>
 @param viewController <#viewController description#>
 @param animated <#animated description#>
 */
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
